<?

/** Formatting related functions.
 *  This collection of functions (libary) is licensed under GPL2.
 *  See LICENSE or www.gnu.org for more details.
 *  @author Jyry Kuukkanen
 */

include_once("sostring.php");
include_once("somath.php");
include_once("sogeneric.php");

/** Returns formatted numeric value.
 *  Numeric value passed is returned in specified format. Format specifies
 *  local settings (thousand delimiter etc.), decimal count and maximum length
 *  or returned string.
 * 
 *  Example: soNumFmt(1234567.6, 2, 0, "") would return "1 234 567.60"
 *  Example: soNumFmt(1234567, 0, 9, "") would return "1 234 568"
 *  Example: soNumFmt(1234567, 0, 8, "") would return "********"
 *  Example: soNumFmt(1234567, 2, 0, "fi") would return "1.234.567,60"
 *
 *  @param any $InValue Numeric value to format.
 *  @param int $Decimals No. of decimals to round up/pad value to.
 *  @param int $MaxChars When set (>0), limits the return string length. A
 *      string of asterisks, stars, is returned if the string to be retured
 *      exceeds this limit.
 *  @param str $FmtKey Key to locale formatting, 2-letter abbreviation, see
 *      soformat.inc for more.
 *  @return string Formatted numeric value.
 */
function soNumFmt($InValue, $Decimals = 0, $MaxChars = 0, 
                  $FmtKey = "default") {
    /* round up to match the no. of decimal */
    $value = soRound($InValue, $Decimals);

    include("soformat.inc");

    /* Get format settings */
    if ($FmtKey == "") $FmtKey = "default";
    $Format = $SO_NUM_FORMATS[$FmtKey];
    if ($Format == NULL) $Format = $SO_NUM_FORMATS["default"];

    $value = number_format(abs($value), $Decimals, $Format[SONF_DDELIM],
                           $Format[SONF_TDELIM]);

    if ($InValue < 0) {
        if ($Format[SONF_NEG_PREFIX]) {
            $prefix = $Format[SONF_NEG_SIGN];
        } else {
            $postfix = $Format[SONF_NEG_SIGN];
        };
        $value = $prefix.$value.$postfix;
    };

    if (($MaxChars != 0) && (strlen($value) > $MaxChars)) {
        $value = soPadStr("", "*", $MaxChars, 0);
    };

    return $value;
}; // soNumFmt



/** Returns bank reference number (Finnish style)
 *  @param int $CustNo Customer number
 *  @param int $InvoiceNo Invoice number
 *  @return int Returns back reference number
 *  @package soformat
 */
function soBankReferenceNo($CustNo, $InvoiceNo) {
    if (!soIsNum($CustNo) || !soisNum($InvoiceNo)) return ""; // <-- EXIT
    $result = intval($CustNo.$InvoiceNo);

    $multipliers = array(1, 7, 3);
    $check_no = 0;
    $icount = strlen($result);
    for ($i = 1; $i <= $icount; $i++) {
        $check_no += substr($result, $icount -$i, 1) 
                     *$multipliers[($i % 3)];
    }; // for $i

    return $result.((10 -($check_no % 10)) % 10);
}; // soBankReferenceNo

?>